using Digitalmes.Common.Jwt;
using Digitalmes.Common.Jwt.Model;
using Microsoft.AspNetCore.Hosting;

namespace Digitalmes.Common.Utils;

/// <summary>
/// APP 应用工具类
/// </summary>
public static class AppUtils
{
    private static IServiceProvider? _serviceProvider;

    /// <summary>
    /// 应用程序配置
    /// </summary>
    [NotNull]
    public static IConfiguration? Configuration { get; private set; }

    /// <summary>
    /// 项目根目录
    /// </summary>
    public static string AppRoot => Environment.CurrentDirectory;

    /// <summary>
    /// 获取项目静态文件根目录 wwwroot
    /// </summary>
    public static string RootPath => GetRequiredService<IWebHostEnvironment>().WebRootPath;

    /// <summary>
    /// 获取请求上下文
    /// </summary>
    public static HttpContext? HttpContext => GetService<IHttpContextAccessor>()?.HttpContext;

    /// <summary>
    /// 获取请求上下文用户
    /// </summary>
    /// <remarks>只有授权访问的页面或接口才存在值，否则为 null</remarks>
    public static ClaimsPrincipal? User => HttpContext?.User;

    /// <summary>
    /// 获取Token信息
    /// </summary>
    public static JwtToken Token
    {
        get
        {
            var paramToken = HttpContext?.Request.Headers["accessToken"].ToString();
            return string.IsNullOrEmpty(paramToken) ? new() : JwtAuthHandler.SerializeJwt(paramToken);
        }
    }

    /// <summary>
    /// 获取登录人编号 Id，没有找到时返回 0。
    /// </summary>
    public static long LoginId
    {
        get
        {
            var userId = HttpContext?.User.FindFirst(nameof(JwtToken.Id))?.Value;
            return !string.IsNullOrEmpty(userId) ? long.Parse(userId) : 0;
        }
    }

    /// <summary>
    /// 获取登录的用户账号，没有找到时返回空。
    /// </summary>
    public static string LoginUser
    {
        get
        {
            var user = HttpContext?.User.FindFirst(nameof(JwtToken.FullName))?.Value;
            return user ?? "";
        }
    }

    /// <summary>
    /// 获取租户编号，没有找到时返回 0。
    /// </summary>
    public static long TenantId
    {
        get
        {
            var tenantId = HttpContext?.User.FindFirst(nameof(JwtToken.TenantId))?.Value;
            return !string.IsNullOrEmpty(tenantId) ? long.Parse(tenantId) : 0;
        }
    }

    /// <summary>
    /// App 初始化操作，在程序启动项处设置
    /// </summary>
    /// <param name="app"></param>
    public static void AppSetup(this IApplicationBuilder app)
    {
        _serviceProvider = app.ApplicationServices;
        Configuration = app.ApplicationServices.GetRequiredService<IConfiguration>();
    }

    public static void AppSetup2(IServiceProvider services)
    {
        _serviceProvider = services;
        Configuration = services.GetRequiredService<IConfiguration>();
    }

    /// <summary>
    /// 获取配置文件实例，若没有配置则返回 default 值。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public static T? GetConfig<T>(string key)
    {
        return Configuration.GetSection(key).Get<T>();
    }

    /// <summary>
    /// 获取注入的对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T? GetService<T>() where T : class
    {
        return _serviceProvider!.GetService<T>();
    }

    /// <summary>
    /// 获取注入的对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T GetRequiredService<T>() where T : notnull => _serviceProvider!.GetRequiredService<T>();
}
